import {ElMessage} from "element-plus";
import axios from "axios";
import {post, sendError, sendSuccess} from "@/utils/request";

/**
 * 登录
 */
export const login = async (username: string, passwd: string) => {
    try {
        if (username.length === 0 || passwd.length === 0) {
            sendError('用户名或密码不能为空');
            return;
        }

        const result = await post('/qa/login', {
            WorkNum: username,
            Passwd: passwd
        });

        if (!result.succeeded) {
            const error = result.errors;

            sendError(error)

            return;
        }

        sendSuccess('登录成功！');

        await auth(username, passwd);

    } catch (error) {
        sendError("登录失败：" + error);
    }
};

/**
 * 获取 token
 */
export const auth = async (username: string, passwd: string) => {
    try {
        const response = await axios.post('/qa/auth', {
            WorkNum: username,
            Passwd: passwd
        });

        if (!response.data.succeeded) {
            const error = response.data.errors;

            ElMessage.error(error)

            return;
        }

        const result = response.data;

        localStorage.setItem('token', result.data);
        localStorage.setItem('expiredTime', '20');

        // 设置定时器，每 20 分钟刷新一次 token
        setInterval(refreshToken, 20 * 60 * 1000);
    } catch (error) {
        sendError("登录失败：" + error);
    }
};

/**
 * 刷新 token
 */
export const refreshToken = async () => {
    try {
        const response = await axios.post('/qa/refresh-token', {
            AccessToken: localStorage.getItem('token'),
            ExpiredTime: localStorage.getItem('expiredTime')
        });

        const newToken = response.data.data;

        localStorage.setItem('token', newToken);

        console.log('Token 已刷新');
        console.log('新的 Token：', newToken)

    } catch (error) {
        sendError("刷新 token 失败：" + error);
    }
};